package org.sang.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;

@Controller
public class LoginController {

//    @PostMapping("/login")
//    public String login(String username, String password) {
//        Subject currentUser = SecurityUtils.getSubject();
//        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
//        try {
//            currentUser.login(token);
//        } catch (AuthenticationException e) {
//            return "login";
//        }
//        return "success";
//    }
    @RequestMapping("/login")
    public String login(HttpServletRequest req, Model model) {
        String shiroLoginFailure = (String) req.getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME);
        if (UnknownAccountException.class.getName().equals(shiroLoginFailure)) {
            model.addAttribute("error", "账户不存在!");
        }
        if (IncorrectCredentialsException.class.getName().equals(shiroLoginFailure)) {
            model.addAttribute("error", "密码不正确!");
        }
        return "login";
    }

}
